import React, { useState, useEffect } from "react";
import { Divider, Button, Table, Pagination, Modal, Form, Input } from "antd";
import { getUserList, deleteUser, editUser } from "../../api/account";
import "./list.less";
import Title from "../../components/Title/Title";
import { message } from "antd";
message.config({
  maxCount: 1, // 只显示一个消息
});

export default function List() {
  const [data, setData] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 8 });
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);

  const onPageChange = (currentpage, pageSize) => {
    console.log("当前页:", currentpage);
    console.log("每页条数:", pageSize);
    setPagination({ current: currentpage, pageSize });
  };

  const onSelectChange = (selectedRowKeys) => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    setSelectedRowKeys(selectedRowKeys);
  };

  const onSelectAllChange = (selected, selectedRows, changeRows) => {
    if (selected) {
      const newSelectedRowKeys = data.map((item) => item.id);
      setSelectedRowKeys(newSelectedRowKeys);
    } else {
      setSelectedRowKeys([]);
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    onSelectAll: onSelectAllChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: "odd",
        text: "Select Odd Row",
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = changeableRowKeys.filter(
            (_, index) => index % 2 !== 0
          );
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: "even",
        text: "Select Even Row",
        onSelect: (changeableRowKeys) => {
          let newSelectedRowKeys = changeableRowKeys.filter(
            (_, index) => index % 2 === 0
          );
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };
  // 在 useEffect 外部定义 fetchData 函数
  const fetchData = async () => {
    try {
      const res = await getUserList({
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      });
      if (Array.isArray(res.data.data)) {
        setData(res.data.data);
      }
    } catch (error) {
      console.error(error);
    }
  };
  useEffect(() => {


    fetchData();
  }, [pagination.current, pagination.pageSize]);

  const handleDelete = async (id) => {
    try {
      const res = await deleteUser(id);
      console.log(res.data);
      if (res.data.code===0) {
        const newData = data.filter((item) => item.id !== id);
        // setData(newData);
        setData(newData, () => {
          fetchData();
        });
        message.success("删除成功");
        fetchData(); // 调用 fetchData 来重新获取数据
      }
    } catch (error) {
      console.error("", error);
    }
  };

  const columns = [
    {
      title: "账号",
      dataIndex: "account",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "用户组",
      dataIndex: "userGroup",
    },
    {
      title: "创建时间",
      dataIndex: "ctime",
    },
    {
      title: "操作",
      dataIndex: "x",
      render: (text, record) => (
        <>
          <Button type="primary" onClick={() => showEditModal(record)}>
            编辑
          </Button>
          ,
          <Button
            type="primary"
            danger
            onClick={() => handleDelete({ id: record.id })}
          >
            删除
          </Button>
        </>
      ),
    },
  ];

  const showEditModal = (user) => {
    setEditingUser(user);
    setEditModalVisible(true);
  };

  const handleEditSubmit = async (editedUser) => {
    try {
      const res = await editUser(editedUser);
      console.log(res.data);
      if (res.data.code===0) {
        const updatedData = data.map((user) =>
          user.id === editedUser.id ? editedUser : user
        );
        // setData(updatedData);
        setData(updatedData, () => {
          fetchData();
          setEditModalVisible(false);
        });
    
      }
    } catch (error) {
      console.error(error);
    }
  };

  const EditUserForm = ({ user, onSubmit }) => {
    const [account, setAccount] = useState(user ? user.account : "");
    const [userGroup, setUserGroup] = useState(user ? user.userGroup : "");

    const handleSubmit = (e) => {
      e.preventDefault();
      onSubmit({ id: user.id, account, userGroup });
      setEditModalVisible(false);
      fetchData();
      
    };

    return (
      <Form onSubmit={handleSubmit}>
        <Form.Item label="账号">
          <Input value={account} onChange={(e) => setAccount(e.target.value)} />
        </Form.Item>
        <Form.Item label="用户组">
          <Input
            value={userGroup}
            onChange={(e) => setUserGroup(e.target.value)}
          />
        </Form.Item>
        <Button type="primary" htmlType="submit" onClick={handleSubmit}>
          提交
        </Button>
      </Form>
    );
  };

  return (
    <>
      <div className="list">
        <div className="add">
          <Title title="账号列表" />
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={data}
          pagination={{
            current: pagination.current,
            total: 500,
            pageSize: pagination.pageSize,
            onChange: onPageChange,
          }}
        />

        <Modal
          title="编辑账号"
          visible={editModalVisible}
          onCancel={() => setEditModalVisible(false)}
          footer={null}
        >
          <EditUserForm user={editingUser} onSubmit={handleEditSubmit} />
        </Modal>
      </div>
    </>
  );
}
